package com.icart.restful;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;
import org.springframework.web.client.AsyncRestTemplate;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.stream.Stream;

/**
 * Created by kim on 18/1/23.
 * 获取和读写远程图片
 */
@Component
@EnableCaching
public class ImageService {

    private static Logger logger= LoggerFactory.getLogger(ImageService.class);

    public static final String BaseURL="http://apis.ikartek.com";

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    AsyncRestTemplate asyncRestTemplate;



    private HttpHeaders getHttpHeaders(String fileName){
        int start= fileName.lastIndexOf(".");
        String ext= fileName.substring(start+1).toLowerCase();

        HttpHeaders headers=new HttpHeaders();
        switch (ext){
            case "jpg":
            case "jpeg":
                headers.setContentType(MediaType.IMAGE_JPEG);
                break;
            case "png":
                headers.setContentType(MediaType.IMAGE_PNG);
                break;
            default:
                headers.setContentType(MediaType.IMAGE_JPEG);
                break;
        }
        return headers;
    }
    /*
    获取远程图片
     */
    @Cacheable(value = {"get"},key = "#fileName",unless="#result == null")
    public ResponseEntity<byte[]> get(String fileName){
        String url=BaseURL+ "/v1/imageservice/image/get?filename=" + fileName;

        HttpHeaders headers= getHttpHeaders(fileName);


        ResponseEntity<byte[]>  responseEntity=  restTemplate.exchange(url, HttpMethod.GET,new HttpEntity<byte[]>(headers),byte[].class);


        return responseEntity;

    }

    /*
    获取远程图片(异步）
    to do
    */
    @Cacheable(value = {"getAsync"},key = "#fileName",unless="#result == null")
    public  ListenableFuture<ResponseEntity<byte[]>> getAsync(String fileName){
        String url=BaseURL+ "/v1/imageservice/image/get?filename=" + fileName;

        HttpHeaders headers= getHttpHeaders(fileName);

        HttpEntity<byte[]> requestEntity=new HttpEntity<>(headers);
        ListenableFuture<ResponseEntity<byte[]>> responseEntityListenableFuture=  asyncRestTemplate.exchange(url,HttpMethod.GET,requestEntity,byte[].class);
        responseEntityListenableFuture.addCallback(new ListenableFutureCallback<ResponseEntity<byte[]>>() {

            @Override
            public void onFailure(Throwable throwable) {
                logger.error("异步读取远程图片出错：");
                logger.error(throwable.getMessage());
                System.out.println("控制台输出：");
                System.out.println(throwable.getMessage());
            }

            @Override
            public void onSuccess(ResponseEntity<byte[]> responseEntity) {
                logger.info("异步读取远程图片成功：");
            }
        });
       //to do
        return responseEntityListenableFuture;

    }
}
